package com.wr.elasticsearch.service;

import com.alibaba.fastjson.JSON;
import com.wr.elasticsearch.entity.Content;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class SearchServiceImpl {

    @Autowired
    private RestHighLevelClient restHighLevelClient;


    public List<Content> search(String keywords,int pageNum,int pageSize) throws IOException {
        SearchRequest searchRequest = new SearchRequest("jd-goodslist");

        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

        // 分页
        searchSourceBuilder.from(pageNum);
        searchSourceBuilder.size(pageSize);

        // 设置高亮字段  requireFieldMatch(true)是否多个相同的词高亮

        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("name").preTags("<span style='color:red'>").postTags("</span>").requireFieldMatch(true);
        searchSourceBuilder.highlighter(highlightBuilder);

        // 匹配查询
        MatchQueryBuilder queryBuilder = QueryBuilders.matchQuery("name", keywords);
        searchSourceBuilder.query(queryBuilder);
        searchSourceBuilder.timeout(TimeValue.timeValueSeconds(60));
        // 执行查询
        searchRequest.source(searchSourceBuilder);
        SearchResponse search = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);

        // 解析结果
        ArrayList<Content> contents = new ArrayList<>();
        for (SearchHit searchHit : search.getHits().getHits()) {
            // 解析高亮字段
            HighlightField name = searchHit.getHighlightFields().get("name");
            // 原来的字段
            Map<String, Object> sourceAsMap = searchHit.getSourceAsMap();

            // 把高亮字段替换原来的字段
            if (name!=null){
                Text[] fragments = name.fragments();
                String n_name="";
                for (Text fragment : fragments) {
                    n_name+=fragment;
                }
                sourceAsMap.put("name",n_name);
            }
            Content content = JSON.toJavaObject((JSON)JSON.toJSON(sourceAsMap),Content.class);
            contents.add(content);
        }
        return contents;

    }
}
